import tkinter as tk
from tkinter import messagebox
from flask import Flask, request, jsonify
import threading
import time
from werkzeug.serving import make_server
import json  # Add this import

class APIReceiver:
    def __init__(self, root):
        self.root = root
        self.root.title("API 接收端 v2.1")
        
        # 默认配置
        self.host = "127.0.0.1"
        self.port = 5000
        self.api_path = "/api/reportApi/report"  # 修改为要求的默认路径
        self.server = None
        self.server_thread = None
        self.app = None  # 初始化时不创建 Flask 实例
        
        # 历史记录
        self.history = []
        self.max_history = 20
        
        # 初始化UI
        self.setup_ui()

    def setup_ui(self):
        """设置用户界面"""
        # 主框架
        main_frame = tk.Frame(self.root, padx=10, pady=10)
        main_frame.pack(expand=True, fill=tk.BOTH)
        
        # 配置区域
        config_frame = tk.LabelFrame(main_frame, text="服务器配置")
        config_frame.pack(fill=tk.X, pady=5)
        
        # 地址配置
        tk.Label(config_frame, text="监听地址:").grid(row=0, column=0, sticky=tk.W)
        self.host_entry = tk.Entry(config_frame, width=15)
        self.host_entry.insert(0, self.host)
        self.host_entry.grid(row=0, column=1, sticky=tk.W)
        
        # 端口配置
        tk.Label(config_frame, text="端口:").grid(row=0, column=2, sticky=tk.W)
        self.port_entry = tk.Entry(config_frame, width=8)
        self.port_entry.insert(0, str(self.port))
        self.port_entry.grid(row=0, column=3, sticky=tk.W)
        
        # API路径配置
        tk.Label(config_frame, text="接收路径:").grid(row=1, column=0, sticky=tk.W)
        self.path_entry = tk.Entry(config_frame, width=25)
        self.path_entry.insert(0, self.api_path)
        self.path_entry.grid(row=1, column=1, columnspan=3, sticky=tk.W)
        
        # 控制按钮
        btn_frame = tk.Frame(main_frame)
        btn_frame.pack(fill=tk.X, pady=5)
        
        self.start_btn = tk.Button(btn_frame, text="启动服务器", command=self.start_server)
        self.start_btn.pack(side=tk.LEFT)
        
        self.stop_btn = tk.Button(btn_frame, text="停止服务器", command=self.stop_server, state=tk.DISABLED)
        self.stop_btn.pack(side=tk.LEFT, padx=5)
        
        # 状态显示
        self.status_var = tk.StringVar(value="状态: 未运行")
        tk.Label(main_frame, textvariable=self.status_var, fg="red").pack(anchor=tk.W)
        
        # 历史记录
        history_frame = tk.LabelFrame(main_frame, text="接收记录")
        history_frame.pack(fill=tk.BOTH, expand=True)
        
        self.history_text = tk.Text(history_frame, height=12, width=70)
        self.history_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        
        scrollbar = tk.Scrollbar(history_frame)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.history_text.config(yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.history_text.yview)
        
        # 右键菜单
        self.context_menu = tk.Menu(self.root, tearoff=0)
        self.context_menu.add_command(label="清空记录", command=self.clear_history)
        self.history_text.bind("<Button-3>", self.show_context_menu)

    def setup_flask_route(self):
        """设置Flask路由（只注册一次路由，不再清空 url_map）"""
        @self.app.route(self.api_path, methods=['POST'])
        def handle_request():
            data = request.get_json()
            if data:
                self.add_history(f"收到数据: {json.dumps(data, indent=2, ensure_ascii=False)}")
                return jsonify({"status": "success", "received": True}), 200
            return jsonify({"status": "error", "message": "Invalid data"}), 400

    def update_config(self):
        """更新配置参数"""
        self.host = self.host_entry.get().strip() or "127.0.0.1"
        try:
            self.port = int(self.port_entry.get().strip() or "5000")
        except ValueError:
            messagebox.showerror("错误", "端口必须是数字")
            return False
        
        new_path = self.path_entry.get().strip()
        if not new_path.startswith('/'):
            messagebox.showerror("错误", "API路径必须以/开头")
            return False
        
        self.api_path = new_path or "/api/reportApi/report"
        return True

    def start_server(self):
        """启动服务器"""
        if not self.update_config():
            return
        try:
            # 每次启动都新建 Flask 实例和注册路由
            self.app = Flask(__name__)
            self.setup_flask_route()
            self.server = make_server(self.host, self.port, self.app)
            self.server_thread = threading.Thread(target=self.server.serve_forever)
            self.server_thread.daemon = True
            self.server_thread.start()
            self.start_btn.config(state=tk.DISABLED)
            self.stop_btn.config(state=tk.NORMAL)
            self.status_var.set(f"状态: 运行中 - {self.host}:{self.port}{self.api_path}")
            self.add_history(f"服务器已启动，监听路径: {self.api_path}")
        except Exception as e:
            messagebox.showerror("错误", f"启动服务器失败: {str(e)}")
            self.add_history(f"启动失败: {str(e)}")

    def stop_server(self):
        """停止服务器"""
        if self.server:
            self.server.shutdown()
            self.server = None
            self.server_thread = None
            self.app = None  # 停止时销毁 Flask 实例
            self.start_btn.config(state=tk.NORMAL)
            self.stop_btn.config(state=tk.DISABLED)
            self.status_var.set("状态: 未运行")
            self.add_history("服务器已停止")

    def add_history(self, message):
        """添加历史记录"""
        self.history.append(message)
        if len(self.history) > self.max_history:
            self.history.pop(0)
        
        # 显示时最新在最上面
        self.history_text.delete(1.0, tk.END)
        self.history_text.insert(tk.END, "\n".join(reversed(self.history)))

    def clear_history(self):
        """清空历史记录"""
        self.history = []
        self.history_text.delete(1.0, tk.END)

    def show_context_menu(self, event):
        """显示右键菜单"""
        self.context_menu.post(event.x_root, event.y_root)

if __name__ == "__main__":
    root = tk.Tk()
    app = APIReceiver(root)
    root.mainloop()